<template>
  <div class="register-container">
    <el-card class="register-card">
      <h2>注册</h2>
      <el-form 
        ref="registerFormRef"
        :model="registerForm" 
        :rules="rules"
        @keyup.enter="handleRegister"
      >
        <!-- API错误信息 -->
        <el-alert
          v-if="apiError"
          :title="apiError"
          type="error"
          :closable="false"
          class="mb-4"
        />

        <el-form-item prop="email">
          <el-input 
            v-model.trim="registerForm.email" 
            placeholder="邮箱（用于登录和找回密码）" 
            :disabled="formLoading"
          >
            <template #prefix>
              <el-icon><Message /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="username">
          <el-input 
            v-model.trim="registerForm.username" 
            placeholder="用户名（选填）" 
            :disabled="formLoading"
          >
            <template #prefix>
              <el-icon><User /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password">
          <el-input 
            v-model.trim="registerForm.password" 
            type="password" 
            placeholder="密码" 
            :disabled="formLoading"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item prop="password2">
          <el-input 
            v-model.trim="registerForm.password2" 
            type="password" 
            placeholder="确认密码" 
            :disabled="formLoading"
            show-password
          >
            <template #prefix>
              <el-icon><Lock /></el-icon>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item>
          <el-button 
            type="primary" 
            @click="handleRegister" 
            :loading="formLoading"
            style="width: 100%"
          >
            注册
          </el-button>
        </el-form-item>

        <div class="login-link">
          已有账号？<router-link to="/login">立即登录</router-link>
        </div>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { User, Lock, Message } from '@element-plus/icons-vue'
import { register } from '@/api/user'
import { setToken } from '@/utils/cookies'

const router = useRouter()
const registerFormRef = ref(null)
const formLoading = ref(false)
const apiError = ref('')

const registerForm = reactive({
  email: '',
  username: '',  // 可选
  password: '',
  password2: ''  // 可选
})

const validatePass2 = (rule, value, callback) => {
  if (value === '') {
    callback(new Error('请再次输入密码'))
  } else if (value !== registerForm.password) {
    callback(new Error('两次输入密码不一致!'))
  } else {
    callback()
  }
}

const rules = {
  email: [
    { required: true, message: '请输入邮箱', trigger: 'blur' },
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  username: [
    { min: 3, max: 30, message: '用户名长度在3-30个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, max: 20, message: '密码长度在6-20个字符之间', trigger: 'blur' }
  ],
  password2: [
    { required: true, message: '请再次输入密码', trigger: 'blur' },
    { validator: validatePass2, trigger: 'blur' }
  ]
}

const handleRegister = async () => {
  if (formLoading.value) return
  
  try {
    apiError.value = ''  // 清除之前的错误信息
    await registerFormRef.value.validate()
    formLoading.value = true
    const res = await register(registerForm)
    setToken(res.token)
    ElMessage.success('注册成功')
    router.push('/')
  } catch (error) {
    apiError.value = JSON.stringify(error.response?.data || error.message, null, 2)
  } finally {
    formLoading.value = false
  }
}
</script>

<style scoped>
.register-container {
  display: flex;
  justify-content: center;
  align-items: center;
  min-height: calc(100vh - 60px);
  background-color: #f5f7fa;
}

.register-card {
  width: 100%;
  max-width: 400px;
}

.register-card h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #303133;
}

.login-link {
  text-align: center;
  margin-top: 16px;
  font-size: 14px;
}

.login-link a {
  color: var(--el-color-primary);
  text-decoration: none;
}

.login-link a:hover {
  text-decoration: underline;
}
</style>
